package cn.msqweb.controller;

import cn.hutool.core.date.DateUtil;

import cn.msqweb.config.AliYunOSSConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;

/**
 * 文件上传控制层
 */
@Api(tags = "文件接口管理")
@RequestMapping("admin/file")
@RestController
public class FileController {

    @Autowired
    private AliYunOSSConfig aliYunOSSConfig;

    /**
     * 上传请求方式只能是:post
     * @return
     */
    @ApiOperation("上传单个图片")
    @PostMapping("upload/element")
    public String uploadFile(@ApiParam("文件对象") MultipartFile file) {

        // 创建日期文件夹名称
        String newFolderName = DateUtil.format(new Date(), "yyyy-MM-dd");
        // 创建时间戳为文件新名称
        String newFileName = DateUtil.format(new Date(), "HHmmssSSS");
        // 获取原文件的后缀名称
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = newFolderName+"/"+newFileName+suffixName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliYunOSSConfig.getEndpoint(),aliYunOSSConfig.getAccessKeyID(),aliYunOSSConfig.getAccessKeySecret());
        URL url = null;
        try {

            ossClient.putObject(aliYunOSSConfig.getBucketName(), objectName, file.getInputStream());
            // 生成url
            url = ossClient.generatePresignedUrl(aliYunOSSConfig.getBucketName(), objectName, DateUtil.offsetDay(new Date(), 365 * 10));

        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url.toString();
    }
}
